package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Transactional
    @Override
    public String createOrder(CreateOrderRequest request) {
        // 创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        // 启动pipeline
        invoker.start(); // 启动流程（pipeline来处理）

        // 获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        // 从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    /**
     * 修改order表的status
     * 修改orderItem的stock
     *
     * @param orderId
     */
    @Transactional
    @Override
    public void cancelOrder(String orderId) {
        // 修改order表的status
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        Order order = orderMapper.selectOneByExample(example);
        Integer status = order.getStatus();
        if (status != 0) {
            throw new BizException(OrderRetCode.CANNOT_CANCEL.getCode(),OrderRetCode.CANNOT_CANCEL.getMessage());
        }
        order.setStatus(7);
        orderMapper.updateByExampleSelective(order, example);
        // 修改orderItem表的status
        Example itemExample = new Example(OrderItem.class);
        Example.Criteria criteria1 = itemExample.createCriteria();
        criteria1.andEqualTo("orderId", orderId);
        OrderItem orderItem = new OrderItem();
        orderItem.setStatus(2);
        orderItemMapper.updateByExampleSelective(orderItem, itemExample);
    }

    /**
     * 根据订单ID删除订单
     * 需要删除三个表
     *
     * @param orderId
     */
    @Transactional
    @Override
    public void deleteOrder(String orderId) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        // 取出order的status
        Order order = orderMapper.selectOneByExample(example);
        Integer status = order.getStatus();
        // 删除并恢复库存
        if (status < 4) {
            throw new BizException(OrderRetCode.CANNOT_DELETE.getCode(),OrderRetCode.CANNOT_DELETE.getMessage());
        }
        // 删除订单
        orderMapper.deleteByExample(example);
        Example itemExample = new Example(OrderItem.class);
        Example.Criteria itemCriteria = example.createCriteria();
        itemCriteria.andEqualTo("orderId", orderId);
        orderItemMapper.deleteByExample(example);
        Example shippingExample = new Example(OrderShipping.class);
        Example.Criteria shippingCriteria = example.createCriteria();
        shippingCriteria.andEqualTo("orderId", orderId);
        orderShippingMapper.deleteByExample(example);
    }

    @Transactional
    @Override
    public void updateOrder(Integer status, String orderId) {
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        if (status == 2) {
            criteria.andEqualTo("status", status);
        }
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

        Iterator<OrderItem> iterator = orderItems.iterator();
        while (iterator.hasNext()) {
            OrderItem orderItem = iterator.next();
            // 获得stock
            Example example1 = new Example(Stock.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("itemId", orderItem.getItemId());
            List<Stock> stocks = stockMapper.selectByExample(example1);
            Stock stock = stocks.get(0);
            Integer lockCount = stock.getLockCount();
            Long stockCount = stock.getStockCount();
            // 获得商品的数量
            Integer num = orderItem.getNum();

            // 修改stock表
            Stock stock1 = new Stock();
            stock1.setStockCount(stockCount + num);
            stock1.setLockCount(lockCount - num);
            stockMapper.updateByExampleSelective(stock1, example1);
        }
    }

}
